package main

import (
	"io/ioutil"
	"os"
	"strings"

	"github.com/Desserts/rmcomment"
	log "github.com/Sirupsen/logrus"
	_ "github.com/go-sql-driver/mysql"
)

func exe(records *map[string]Record) {
	sqls := readFile(records)
	executeSql(sqls)
}

func readFile(records *map[string]Record) []string {
	sqls := make([]string, 0)
	for _, v := range *records {
		if v.Sync {
			fi, err := os.Open(path + "/" + v.Name)
			defer fi.Close()
			if err != nil {
				log.Error("read file error: ", err)
			}
			bytearr, _ := ioutil.ReadAll(fi)
			str := string(bytearr)
			str = rmcomment.Rm(str)
			sqls = append(sqls, str)
		}
	}
	return sqls
}

func executeSql(scripts []string) {
	passSql := make([]string, 0)
	badSql := make(map[string]string)
	for _, sqls := range scripts {
		sql2 := strings.Split(sqls, ";")
		for _, sql := range sql2 {
			sql := strings.TrimSpace(sql)
			if len(sql) > 0 {
				_, err := engine.Exec(sql)
				if err != nil {
					log.Error("execute sql error: ", err)
					log.Info("wrong sql: ", sql)
					badSql[sql] = err.Error()
				} else {
					log.Info("exexute sql success")
					log.Info("sql: ", sql)
					passSql = append(passSql, sql)
				}
			}
		}
	}
	if len(passSql) > 0 || len(badSql) > 0 {
		sendMail(passSql, badSql)
	}
}

func sendMail(passSql []string, badSql map[string]string) {
	configtitle, _ := config.GetValue("config", "title")
	title := " [sync db] from (" + configtitle + ")"
	status := "success"
	content := ""
	if len(passSql) > 0 {
		content +=
			`<h3>执行成功的SQL</h3>
			<ol>
	`
		for _, v := range passSql {
			content += "<li>" + v + "</li>"
		}
		content += "</ol>"
	}

	if len(badSql) > 0 {
		status = "fail"
		content += `<br/>
		<h3>执行失败的SQL</h3>
		<ol>
		`
		for k, v := range badSql {
			content += "<li>" + k + "</li>"
			content += "<div style='color:red'>&nbsp;&nbsp;" + v + "</div>"
		}
		content += "</ol>"
	}
	if len(content) > 0 {
		email.SendMail(to, status+title, content)
	}
}
